<?php


namespace app\controller;

use app\facade\SheetXlsx;
use app\model\Lv;
use app\model\LvReceive;
use app\model\Substrates;
use app\model\Tai;
use app\model\TaiReceive;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\facade\Db;
use think\facade\Filesystem;

class RawMaterialController
{
    //用户认证中间件
    protected $middleware = ['AuthCheck'];

    //获取所有钛粉末库存
    public function getTai()
    {
        return rejson(1, ['tai' => Tai::select()]);
    }

    //获取所有铝粉末库存
    public function getLv()
    {
        return rejson(1, ['lv' => Lv::select()]);
    }

    //获取所有钛合金粉末领用记录
    public function getTaiReceive()
    {
        return rejson(1, ['taiReceives' => TaiReceive::select()]);
    }

    //获取所有铝合金粉末领用记录
    public function getLvReceive()
    {
        return rejson(1, ['lvReceives' => LvReceive::select()]);
    }

    //钛合金粉，写入上传的xlsx文件数据
    public function taiReceive()
    {
        //验证是否上传文件
        if (!request()->has('taiSheet', 'file')) {
            return rejson(0, null, '请上传文件', 412);
        }
        $username = input('post.username');
        //获取文件并保存
        $taiSheet = request()->file('taiSheet');
        $savePath = 'tai/' . date('Y-m-d', time());
        $taiSheetName = Filesystem::disk('excel')->putFile($savePath, $taiSheet, function () {
            return date('YmdHis', time());
        });
        $taiSheetPath = app()->getRootPath() . 'storage/excel/' . $taiSheetName;
        //解析文件数据
        $sheetDatas = SheetXlsx::get($taiSheetPath, 'A', 'B');
        array_shift($sheetDatas);
        //开启事务
        Db::startTrans();
        // A:批次号	B:领用数量（KG）	C:领用日期	D:领用人
        try {
            $saveDatas = [];
            foreach ($sheetDatas as $data) {
                //获取批次号对应的库存
                $tai = Tai::getByBatch($data['A']);
                //计算剩余并保存
                $remnant_num = (int)$tai->stock - (int)$data['B'];
                $tai->stock = $remnant_num;
                $tai->save();
                $saveDatas[] = [
                    'tai_batch' => $tai->batch,
                    'original_num' => $tai->stock,
                    'receive_num' => $data['B'],
                    'remnant_num' => $remnant_num,
                    'receive_date' => gt(),
                    'collar' => $username
                ];
            }
            //保存所有记录
            $TaiReceive = new TaiReceive();
            $taiReceives = $TaiReceive->saveAll($saveDatas);
            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            unlink($taiSheetPath);
            //回滚事务
            Db::rollback();
            return rejson(0, null, '数据添加失败,请重试', 500);
        }
        return rejson(1, ['taiReceives' => $taiReceives]);
    }

    //铝合金粉，写入上传的xlsx文件数据
    public function lvReceive()
    {
        //验证是否上传文件
        if (!request()->has('lvSheet', 'file')) {
            return rejson(0, null, '请上传文件', 412);
        }
        $username = input('post.username');
        //获取文件并保存
        $lvSheet = request()->file('lvSheet');
        $savePath = 'lv/' . date('Y-m-d', time());
        $lvSheetName = Filesystem::disk('excel')->putFile($savePath, $lvSheet, function () {
            return date('YmdHis', time());
        });
        $lvSheetPath = app()->getRootPath() . 'storage/excel/' . $lvSheetName;
        //解析文件数据
        $sheetDatas = SheetXlsx::get($lvSheetPath, 'A', 'B');
        array_shift($sheetDatas);
        //开启事务
        Db::startTrans();
        // A:批次号	B:领用数量（KG）	C:领用日期	D:领用人
        try {
            $saveDatas = [];
            foreach ($sheetDatas as $data) {
                //获取批次号对应的库存
                $lv = Lv::getByBatch($data['A']);
                //计算剩余并保存
                $remnant_num = (int)$lv->stock - (int)$data['B'];
                $lv->stock = $remnant_num;
                $lv->save();
                $saveDatas[] = [
                    'lv_batch' => $lv->batch,
                    'original_num' => $lv->stock,
                    'receive_num' => $data['B'],
                    'remnant_num' => $remnant_num,
                    'receive_date' => gt(),
                    'collar' => $username
                ];
            }
            //保存所有记录
            $LvReceive = new LvReceive();
            $lvReceives = $LvReceive->saveAll($saveDatas);
            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            unlink($lvSheetPath);
            //回滚事务
            Db::rollback();
            return rejson(0, null, '数据添加失败,请重试',500);
        }
        return rejson(1, ['lvReceives' => $lvReceives]);
    }

    //获取基板库存
    public function getSubstrates()
    {
        return rejson(1, ['substrates' => Substrates::select()]);
    }

    //基板写入xlsx文件数据
    public function substrates()
    {
        //验证是否上传文件
        if (!request()->has('subSheet', 'file')) {
            return rejson(0, null, '请上传文件', 412);
        }
        $username = input('post.username');
        //获取文件并保存
        $subSheet = request()->file('subSheet');
        $savePath = 'sub/' . date('Y-m-d', time());
        $subSheetName = Filesystem::disk('excel')->putFile($savePath, $subSheet, function () {
            return date('YmdHis', time());
        });
        $subSheetPath = app()->getRootPath() . 'storage/excel/' . $subSheetName;
        //解析文件数据
        $sheetDatas = SheetXlsx::get($subSheetPath, 'A', 'C');
        array_shift($sheetDatas);
        //开启事务
        Db::startTrans();
        // A:编号	B:状态	C:厚度(mm)
        try {
            $saveDatas = [];
            foreach ($sheetDatas as $data) {
                $saveDatas[] = [
                    'number' => $data['A'],
                    'status' => $data['B'],
                    'thick' => $data['C'],
                    'noteTaker' => $username,
                    'date' => gt(),
                ];
            }
            //保存所有记录
            $Substrates = new Substrates();
            $substrates = $Substrates->saveAll($saveDatas);
            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            unlink($subSheetPath);
            //回滚事务
            Db::rollback();
            return rejson(0, null, '数据添加失败,请重试',500);
        }
        return rejson(1, ['substrates' => $substrates]);
    }

    //下载钛粉末领用数据--待定
    /*    public function dLoadTaiRec()
        {
    
            $sheetHeader = ['序号', '批次号', '原始库存(KG)', '领用数量(KG)', '剩余库存(KG)', '领用日期', '领用人'];
    
            $spreadSheet = new Spreadsheet();
            $spreadSheet->getActiveSheet()->setTitle('sheet1');
            $spreadSheet->getActiveSheet()->fromArray($sheetHeader, null, 'A1');
            $file_name = date('Y-m-d_H.i.s', time()) . ".xlsx";
            ob_end_clean();
            header("Access-Control-Allow-Origin:*");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header("Content-Disposition:attachment;filename=$file_name");
            header('Cache-Control: max-age=0');//禁止缓存
            $objWriter = IOFactory::createWriter($spreadSheet, 'Xlsx');
            $objWriter->save('php://output');
            $spreadSheet->disconnectWorksheets();
            unset($spreadsheet);
            exit;
        }*/
}